package com.clp.util.math;

import com.clp.util.exception.EnumElemDoesNotExistException;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 二元运算符
 */
@Getter
@AllArgsConstructor
public enum BinOp {
    /**
     * 加
     */
    ADD(1, '+') {
        @Override
        public BigDecimal calculate(BigDecimal leftVal, BigDecimal rightVal) {
            return leftVal.add(rightVal);
        }
    },
    /**
     * 减
     */
    SUB(1, '-') {
        @Override
        public BigDecimal calculate(BigDecimal leftVal, BigDecimal rightVal) {
            return leftVal.subtract(rightVal);
        }
    },
    /**
     * 乘
     */
    MUL(2, '*') {
        @Override
        public BigDecimal calculate(BigDecimal leftVal, BigDecimal rightVal) {
            return leftVal.multiply(rightVal);
        }
    },
    /**
     * 除
     */
    DIV(2, '/') {
        @Override
        public BigDecimal calculate(BigDecimal leftVal, BigDecimal rightVal) {
            return leftVal.divide(rightVal, RoundingMode.HALF_UP);
        }
    };

    private final int priority; // 优先级，值越大优先级越大
    private final char val;

    public abstract BigDecimal calculate(BigDecimal leftVal, BigDecimal rightVal);

    public static BinOp gain(char val) {
        for (BinOp op : BinOp.values()) {
            if (op.val == val) {
                return op;
            }
        }
        throw new EnumElemDoesNotExistException(BinOp.class);
    }

    public static boolean isBinOp(char val) {
        try {
            BinOp op = gain(val);
            return true;
        } catch (EnumElemDoesNotExistException e) {
            return false;
        }
    }
}
